<template>
	<view class="units">
		<view class="units-head">
			<u-subsection @change="onDay" :list="dayList" :current="current"></u-subsection>
		</view>
		<view class="units-text">
			<view class="">
				<rich-text style="color: #303133;">
					当前类目：
				</rich-text>
			</view>
			<view style="width: 450rpx;">
				<up-button size="mini" @click="showCategory = !showCategory" icon="arrow-down-fill" :plain="true">
					<rich-text style="color: #409EFF;">
						{{category}}
					</rich-text>
				</up-button>
			</view>
		</view>
		<view class="units-content">
			<view class="units-counts">
				<view class="units-counts-line">
					<u-line-progress :showText="false" :percentage="percentage" />
				</view>
				<view class="units-counts-test">
					<view style="display: flex; justify-content:start; align-items:center;">
						<view class="units-counts-test-left"></view>
						<view class="units-counts-test-rigth">
							<text>
								{{category}}
							</text>
						</view>
					</view>
					<view style="font-size: 8px;">
						记录次数：{{percentage}}
					</view>
				</view>
				<view class="units-counts-data" v-if="percentage > 0">
					<qiun-data-charts type="column" :opts="opts" :chartData="chartData" :ontouch="true" />
				</view>
				<view class="units-counts-data" v-if="percentage < 1">
					<view style="width: 100%; height: 100%; display: flex;align-items: center;justify-content: center;">
						<u-empty iconColor="#409EFF" mode="history"></u-empty>
					</view>
				</view>
				<view class="units-abstract" v-if="false">
					<text>
						物联网消防报警记录
					</text>
					<view class="units-abstract-son">
						<view class="units-abstract-son-ones">
							<view style="width: 95%; margin: auto; text-align: center; margin-top: 10rpx;">
								<text style=" color: rgb(280, 107, 77); font-size: 14px;">
									感烟火灾探测器
								</text>
								<view>
									<text v-if="smokeFireDetector == 0" style="color: #CCCCCC; font-size: 12px;">
										暂无数据
									</text>
								</view>
								<view style="margin-top: 10%;">
									<rich-text style="font-size: 30px; font-weight:bold;">{{smokeFireDetector}}</rich-text><rich-text style="color: #CCCCCC;">次</rich-text>
								</view>
							</view>
						</view>
						<view class="units-abstract-son-ones">
							<view style="width: 95%; margin: auto; text-align: center; margin-top: 10rpx;">
								<text style=" color: rgb(280, 107, 77); font-size: 14px;">
									复合火灾探测器
								</text>
								<view>
									<text v-if="compositeFireDetector == 0" style="color: #CCCCCC; font-size: 12px;">
										暂无数据
									</text>
								</view>
								<view style="margin-top: 10%;">
									<rich-text style="font-size: 30px; font-weight:bold;">{{compositeFireDetector}}</rich-text><rich-text style="color: #CCCCCC;">次</rich-text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view>
			<u-picker @cancel="showCategory = !showCategory" title="请选择要查看的类目" @confirm="onCategory" :show="showCategory" :columns="columns"></u-picker>
		</view>
	</view>
</template>

<script>
	import { BASE_IP } from '@/common/http/url.js'
	import moment from "moment"
	export default {
		name: "units",
		data() {
			return {
				unit: "",
				dayList: ['日', '周', '月'],
				current: 0,
				showCategory: false,
				columns: [
					['每日防火巡查记录表', '灭火器安全检查记录表', '消防控制室值班记录表', '消防栓检查表', '建筑消防设施维护保养和故障维修记录表', '专职、义务消防队人员记录表', '灭火和应急疏散预案演练记录表', '年度消防经费开支统计记录表', '动用明火记录表', '消防监控室制表记录表', '消防安全宣传培训记录表', '消防检查整改记录表', '消防设施管理表', '消防安全日查记录表', '消防定期检查记录表', '消防测试记录表', '消防系统验收表', '消防维保交接清单']
				],
				category: "每日防火巡查记录表",
				percentage: 0,
				chartData: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
					padding: [15, 15, 0, 5],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {
						data: [{
							min: 0
						}]
					},
					extra: {
						column: {
							type: "group",
							width: 30,
							activeBgColor: "#000000",
							activeBgOpacity: 0.08
						}
					}
				},
				records: "",
				newRecords: "",
				index: 0,
				formattedRecords: "",
				chartDataLen: 0,
				smokeFireDetector: 0,
				compositeFireDetector: 0,
				day: 1
			}
		},
		methods: {
			onDay(res) {
				this.current = res
				let d = 1;
				if (res == 0) {
					d = 1;
				} else if (res == 1) {
					d = 7;
				} else if (res == 2) {
					d = 30;
				}
				this.day = d
				this.getUnitDatas(d)
			},
			unitsSort(res) {
				if (res != null && res.code == 500) {
					//接口返回了不同格式
					return;
				}
				const currentDate = moment();
				const formattedDate = currentDate.format('YYYY-MM-DD HH:mm');
				let d = this.day;
				// if (res == 0) {
				// 	d = 1;
				// } else if (res == 1) {
				// 	d = 7;
				// } else if (res == 2) {
				// 	d = 30;
				// }

				const startDate = moment().subtract(d, 'days').startOf('day');
				const endDate = moment();

				const tagetData = res;
				const filteredData = tagetData.filter(item => {
					const recordTime = moment(item.recordTime);
					return recordTime.isBetween(startDate, endDate, null, '[]');
				});

				const sortedData = filteredData.sort((a, b) => {
					const dateA = moment(a.recordTime);
					const dateB = moment(b.recordTime);
					return dateA - dateB;
				});

				this.newRecords = sortedData;
				this.percentage = this.newRecords.length;

				const formattedRecords = sortedData.map(record => {
					const date = moment(record.recordTime);
					const day = date.date();
					const month = date.month() + 1;
					const year = date.year();
					const formattedDate =
						`${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
					return {
						...record,
						recordTime: day + "日"
					};
				});

				// this.formattedRecords = formattedRecords;
				this.getServerData(formattedRecords);
			},
			onCategory(res) {
				this.category = res.value[0]
				this.index = res.indexs[0]
				this.showCategory = !this.showCategory
				this.getUnitDatas(this.day)
			},
			getServerData(formattedRecords) {
				//模拟从服务器获取数据时的延时
				// console.log("调用：" , formattedRecords)
				setTimeout(() => {
					//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接、
					let d = {
						name: "",
						data: []
					};
					let res = {
						categories: [],
						series: []
					};

					let formatted = formattedRecords;

					for (let f in formatted) {
						res.categories.push(formatted[f].recordTime);
					}

					const uniqueCategories = [...new Set(res.categories)];

					const countByRecordTime = {};

					for (const record of formatted) {
						const {
							name,
							recordTime
						} = record;
						const key = name;

						if (!countByRecordTime[key]) {
							countByRecordTime[key] = {};
							countByRecordTime[key].data = [];
						}

						countByRecordTime[key].name = key;
						countByRecordTime[key].data.push(uniqueCategories.indexOf(recordTime) + 1);
					}

					for (const key in countByRecordTime) {
						res.series.push(countByRecordTime[key]);
					}
					const result = {
						categories: uniqueCategories,
						series: res.series
					};
					// console.log("========>",result)
					this.chartData = JSON.parse(JSON.stringify(result));
					console.log(this.chartData)
					this.chartDataLen = this.chartData.length
				}, 500);
			},
			getUnitDatas(day) {
				let classid = 0
				let index = this.index
				switch (index) {
					case 0: {
						classid = 1
						break
					}
					case 1: {
						classid = 2
						break
					}
					case 2: {
						classid = 3
						break
					}
					case 3: {
						classid = 4
						break
					}
					case 4: {
						classid = 5
						break
					}
					case 5: {
						classid = 6
						break
					}
					case 6: {
						classid = 7
						break
					}
					case 7: {
						classid = 8
						break
					}
					case 8: {
						classid = 9
						break
					}
					case 9: {
						classid = 10
						break
					}
					case 10: {
						classid = 11
						break
					}
					case 11: {
						classid = 12
						break
					}
					case 12: {
						classid = 13
						break
					}
					case 13: {
						classid = 14
						break
					}
					case 14: {
						classid = 15
						break
					}
					case 15: {
						classid = 16
						break
					}
				}
				let url = BASE_IP + "pc/record/query/day/" + this.unit.unitID + "/" + classid + "/" + day
				// console.log(url)
				let user = uni.getStorageSync("user")
				let _this = this
				uni.request({
					header: {
						"Authorization": user.token,
					},
					url: url,
					success: (res) => {
						console.log('ucv', res)
						if (res.statusCode == 200) {
							setTimeout(() => {
								if (res.data.length == 0) {
									uni.showModal({
										title: "提示",
										content: "此类目没有数据",
										success: (res) => {
											if (res.confirm) {
												return
											}
										},
										showCancel: false
									})
								}
								_this.records = res.data
								// _this.onDay(_this.current)
								// console.log(res.data)
								_this.unitsSort(res.data)
							}, 500)
							setTimeout(() => {
								_this.records = res.data
								// _this.onDay(_this.current)
							}, 800)
						}
						if (res.statusCode == 500) {
							setTimeout(() => {
								_this.newRecords = [
									[0]
								]
								_this.records = [
									[0]
								]
								_this.formattedRecords = [
									[0]
								]
								// _this.onDay(_this.current)
								_this.percentage = 0
							}, 500)

							setTimeout(() => {
								_this.newRecords = [
									[0]
								]
								_this.records = [
									[0]
								]
								_this.formattedRecords = [
									[0]
								]
								_this.percentage = 0
								// _this.onDay(_this.current)
							}, 800)
							uni.showModal({
								title: "提示",
								content: "此类目没有数据",
								success: (res) => {
									if (res.confirm) {
										return
									}
								},
								showCancel: false
							})
						}
						if (res.statusCode == 404) {
							setTimeout(() => {
								_this.newRecords = [
									[0]
								]
								_this.records = [
									[0]
								]
								_this.formattedRecords = [
									[0]
								]
								// _this.onDay(_this.current)
								_this.percentage = 0
							}, 500)

							setTimeout(() => {
								_this.newRecords = [
									[0]
								]
								_this.records = [
									[0]
								]
								_this.formattedRecords = [
									[0]
								]
								_this.percentage = 0
								// _this.onDay(_this.current)
							}, 800)

							uni.showModal({
								title: "提示",
								content: "查询记录失败，请重试",
								success: (res) => {
									if (res.confirm) {
										return
									}
								},
								showCancel: false
							})
						}
					}
				})
			},
			getInternetThings(day) {
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/iotFireAlarmRecord/query/" + this.unit.unitID
				uni.request({
					header: {
						"Authorization": user.token
					},
					url: url,
					success: (res) => {
						const today = moment();
						const oneWeekAgo = today.clone().subtract(day, 'days');
						const detectorCount = {};

						for (const item of res.data) {
							const date = parseInt(item.date);
							const itemDate = moment({ year: today.year(), month: today.month(), date });
							if (itemDate.isBetween(oneWeekAgo, today, 'day', '[]')) {
								detectorCount[date] = item.smokeFireDetector;
							}
						}
						const sortedDates = Object.keys(detectorCount).sort((a, b) => detectorCount[b] - detectorCount[a]);
						let smokeFireDetector = 0

						for (const date of sortedDates) {
							const count = detectorCount[date];
							smokeFireDetector += count
						}

						const today1 = moment();
						const oneWeekAgo1 = today1.clone().subtract(day, 'days');
						const detectorCount1 = {};

						for (const item1 of res.data) {
							const date = parseInt(item1.date);
							const itemDate = moment({ year: today1.year(), month: today1.month(), date });
							if (itemDate.isBetween(oneWeekAgo1, today1, 'day', '[]')) {
								detectorCount1[date] = item1.compositeFireDetector;
							}
						}
						const sortedDates1 = Object.keys(detectorCount1).sort((a, b) => detectorCount1[b] - detectorCount1[a]);
						let compositeFireDetector = 0

						for (const date of sortedDates1) {
							const count = detectorCount1[date];
							compositeFireDetector += count
						}
						this.smokeFireDetector = smokeFireDetector
						this.compositeFireDetector = compositeFireDetector
						// console.log("感烟火灾探测器：",smokeFireDetector)
						// console.log("复合火灾探测器：",compositeFireDetector)

					}
				})
			}
		},
		onLoad(ops) {
			this.unit = JSON.parse(ops.unit)
			console.log("单位信息：", this.unit)
			// this.getServerData();
			setTimeout(res => {
				this.getUnitDatas(this.day)
				this.getInternetThings(1)
			}, 500)


		}
	}
</script>

<style>
	page {
		background-color: #FFFFFF;
	}

	.units {
		width: 100%;
		height: auto;

	}

	.units-head {
		width: 90%;
		height: auto;
		padding-bottom: 10rpx;
		padding-top: 4rpx;
		margin: auto;
	}

	.units-text {
		width: 90%;
		height: auto;
		padding-top: 10rpx;
		padding-bottom: 10rpx;
		margin: auto;
		display: flex;
		align-items: center;
		justify-content: start;

	}

	.units-counts {
		width: 95%;
		height: 150rpx;
		background-color: #FFFFFF;
		margin: auto;
		border-radius: 15px;
		box-shadow: 1px 1px 1px #CDD0D6;
	}

	.units-counts-line {
		width: 90%;
		height: auto;
		padding-top: 20rpx;
		margin: auto;
	}

	.units-counts-test {
		display: flex;
		height: 100rpx;
		justify-content: space-around;
		align-items: center;
		margin: auto;
	}

	.units-counts-test-left {
		width: 25rpx;
		height: 25rpx;
		background-color: #409EFF;
		margin-right: 20rpx;
	}

	.units-counts-test-rigth {
		font-size: 12px;
	}

	.units-counts-data {
		width: 95%;
		height: 700rpx;
		background-color: #ffffff;
		border-radius: 8px;
		margin: 40rpx auto;
	}

	.units-abstract {
		width: 95%;
		height: auto;
		padding-bottom: 50rpx;
	}

	.units-abstract-son {
		width: 100%;
		height: auto;
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-top: 20rpx;
	}

	.units-abstract-son-ones {
		width: 45%;
		height: 230rpx;
		background-color: #ffffff;
		border-radius: 14px;
	}
</style>